﻿@page "/fetchdata"
@inject HttpClient Http
@inject IPopupService PopupService

<PageTitle>Orders</PageTitle>

<h2>Orers</h2>

<p>This component demonstrates fetching data from a service.</p>

@if (_orders == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <MDataTable Headers="_headers" Items="_orders" ItemsPerPage="5">
        <ItemColContent>
            @if (context.Header.Value == nameof(Order.CreationTime))
            {
                @context.Item.CreationTime.ToShortDateString()
            }
            else
            {
                @context.Value
            }
        </ItemColContent>
    </MDataTable>
}

@code {

    private List<DataTableHeader<Order>> _headers = new List<DataTableHeader<Order>> {
        new (){ Text = "CreationTime",Value = nameof(Order.CreationTime) },
        new (){ Text = "Id",Value = nameof(Order.Id) },
        new (){ Text = "OrderNumber",Value = nameof(Order.OrderNumber) },
        new (){ Text = "Address",Value = nameof(Order.Address),Sortable = false },
    };

    private Order[]? _orders;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            _orders = await Http.GetFromJsonAsync<Order[]>("/api/v1/orders");
        }
        catch (Exception e)
        {
            await PopupService.EnqueueSnackbarAsync(e);
        }
    }

    public class Order
    {
        public DateTime CreationTime { get; set; }

        public int Id { get; set; }

        public string OrderNumber { get; set; } = "";

        public string Address { get; set; } = "";
    }
}

